<template>
  <div class="patrol-container">
    <!-- 页面标题与筛选区 -->
    <div class="patrol-header">
      <h2>巡更管理</h2>
      <el-select
          v-model="selectedCommunity"
          placeholder="选择小区"
          @change="loadPatrolData"
          style="width: 200px;"
      >
        <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
        ></el-option>
      </el-select>
    </div>

    <!-- 功能区 -->
    <div class="patrol-content">
      <!-- 左侧地图区域 -->
      <div class="map-wrapper">
        <div id="mapContainer" class="map-container"></div>
        <el-button
            type="primary"
            @click="startPatrol"
            :disabled="isPatrolling"
            class="start-btn"
        >
          {{ isPatrolling ? '正在巡更中' : '开始巡更' }}
        </el-button>
      </div>

      <!-- 右侧信息区 -->
      <div class="info-wrapper">
        <!-- 巡更点位列表 -->
        <el-card>
          <div slot="header">
            <h3>巡更点位列表</h3>
          </div>
          <el-table
              :data="patrolPoints"
              border
              style="width: 100%;"
          >
            <el-table-column
                prop="name"
                label="点位名称"
                width="120"
            ></el-table-column>
            <el-table-column
                prop="buildingName"
                label="所属楼宇"
                width="100"
            ></el-table-column>
            <el-table-column
                prop="locationNo"
                label="位置编号"
                width="100"
            ></el-table-column>
            <el-table-column
                prop="photoRequire"
                label="拍照要求"
                width="100"
            >
              <template #default="scope">
                <el-tag :type="scope.row.photoRequire ? 'success' : 'info'">
                  {{ scope.row.photoRequire ? '需要' : '不需要' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
                prop="status"
                label="状态"
                width="80"
            >
              <template #default="scope">
                <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
                label="操作"
                width="120"
            >
              <template #default="scope">
                <el-button
                    size="small"
                    type="success"
                    @click="checkIn(scope.row)"
                    :disabled="!isPatrolling"
                >
                  签到
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>

        <!-- 巡更记录 -->
        <el-card style="margin-top: 20px;">
          <div slot="header">
            <h3>今日巡更记录</h3>
          </div>
          <el-table
              :data="patrolRecords"
              border
              style="width: 100%;"
          >
            <el-table-column
                prop="checkInTime"
                label="签到时间"
                width="160"
            ></el-table-column>
            <el-table-column
                prop="pointName"
                label="巡更点位"
                width="120"
            ></el-table-column>
            <el-table-column
                prop="result"
                label="巡检结果"
                width="100"
            >
              <template #default="scope">
                <el-tag :type="scope.row.result === '正常' ? 'success' : 'danger'">
                  {{ scope.row.result }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
                prop="remark"
                label="备注"
            ></el-table-column>
          </el-table>
        </el-card>
      </div>
    </div>

    <!-- 签到弹窗 -->
    <el-dialog
        title="巡更签到"
        :visible.sync="checkInDialogVisible"
        width="400px"
    >
      <el-form :model="checkInForm" ref="checkInFormRef">
        <el-form-item label="巡更点位" prop="pointName">
          <el-input v-model="checkInForm.pointName" disabled></el-input>
        </el-form-item>
        <el-form-item label="巡检结果" prop="result">
          <el-radio-group v-model="checkInForm.result">
            <el-radio label="正常"></el-radio>
            <el-radio label="异常"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
            label="异常说明"
            prop="remark"
            v-if="checkInForm.result === '异常'"
        >
          <el-input
              type="textarea"
              v-model="checkInForm.remark"
              rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item
            label="现场照片"
            prop="photo"
            v-if="currentPoint.photoRequire"
        >
          <el-upload
              action=""
              :on-change="handlePhotoUpload"
              :show-file-list="false"
              accept="image/*"
          >
            <el-button size="small" type="primary">上传照片</el-button>
          </el-upload>
          <img
              v-if="checkInForm.photoUrl"
              :src="checkInForm.photoUrl"
              class="preview-img"
          >
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="checkInDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmCheckIn">确认签到</el-button>
      </div>
    </el-dialog>
  </div>
  <router-view/>
</template>

<script>
import loadBMap from '../utils/loadBMap.js'
import { ElMessage } from 'element-plus'

export default {
  name: "Patrol",
  data() {
    return {
      // 小区列表
      communityList: [
        { id: 1, name: '万象城' },
        { id: 2, name: '万达文旅城' },
        { id: 3, name: '碧桂园' }
      ],
      selectedCommunity: 1, // 默认选中万象城

      // 地图相关
      map: null,
      BMapGL: null,
      markers: [], // 点位标记数组

      // 巡更数据
      patrolPoints: [], // 巡更点位列表
      patrolRecords: [], // 巡更记录

      // 状态控制
      isPatrolling: false, // 是否正在巡更
      checkInDialogVisible: false, // 签到弹窗显示状态
      currentPoint: null, // 当前签到点位

      // 签到表单
      checkInForm: {
        pointId: null,
        pointName: '',
        result: '正常',
        remark: '',
        photoUrl: ''
      }
    }
  },
  mounted() {
    // 初始化地图
    this.initMap()
    // 加载巡更数据
    this.loadPatrolData()
  },
  methods: {
    // 初始化百度地图 111
    async initMap() {
      try {
        // 加载百度地图API（使用环境变量中的AK）
        this.BMapGL = await loadBMap(import.meta.env.VITE_BAIDU_MAP_AK)
        // 创建地图实例
        this.map = new this.BMapGL.Map("mapContainer")
        // 初始化中心点（默认万象城坐标）
        const centerPoint = new this.BMapGL.Point(116.404, 39.915)
        this.map.centerAndZoom(centerPoint, 15)
        // 添加地图控件
        this.map.addControl(new this.BMapGL.NavigationControl())
        this.map.addControl(new this.BMapGL.ScaleControl())
      } catch (error) {
        console.error('地图初始化失败:', error)
        ElMessage.error('地图加载失败，请刷新页面重试')
      }
    },

    // 加载巡更数据
    loadPatrolData() {
      // 模拟后端接口请求
      setTimeout(() => {
        // 模拟巡更点位数据
        this.patrolPoints = [
          {
            id: 1,
            name: '巡更点位一',
            buildingName: '1号楼',
            unit: '1单元',
            locationNo: '1-101',
            longitude: 116.404,
            latitude: 39.915,
            photoRequire: true,
            status: '正常'
          },
          {
            id: 2,
            name: '巡更点位二',
            buildingName: '1号楼',
            unit: '1单元',
            locationNo: '1-102',
            longitude: 116.405,
            latitude: 39.916,
            photoRequire: true,
            status: '正常'
          },
          {
            id: 3,
            name: '巡更点位三',
            buildingName: '2号楼',
            unit: '2单元',
            locationNo: '2-201',
            longitude: 116.406,
            latitude: 39.917,
            photoRequire: false,
            status: '正常'
          }
        ]
        // 在地图上绘制点位
        this.drawPatrolPoints()
      }, 500)
    },

    // 在地图上绘制巡更点位
    drawPatrolPoints() {
      // 清除现有标记
      this.markers.forEach(marker => {
        this.map.removeOverlay(marker)
      })
      this.markers = []

      // 添加新标记
      this.patrolPoints.forEach(point => {
        const position = new this.BMapGL.Point(point.longitude, point.latitude)
        const marker = new this.BMapGL.Marker(position)

        // 点位点击事件
        marker.addEventListener('click', () => {
          const infoWindow = new this.BMapGL.InfoWindow(`
            <div style="padding:10px">
              <h4>${point.name}</h4>
              <p>位置：${point.buildingName}-${point.unit}</p>
              <p>编号：${point.locationNo}</p>
              <p>拍照要求：${point.photoRequire ? '是' : '否'}</p>
              ${this.isPatrolling ?
              `<button onclick="document.querySelector('[data-v-app]').__vue_app__.config.globalProperties.$emit('checkIn', ${point.id})"
                  style="margin-top:5px;padding:3px 8px;background:#1677ff;color:white;border:none;border-radius:3px;">
                  签到
                </button>` : ''
          }
            </div>
          `)
          this.map.openInfoWindow(infoWindow, position)
        })

        this.map.addOverlay(marker)
        this.markers.push(marker)
      })
    },

    // 开始巡更
    startPatrol() {
      this.isPatrolling = true
      ElMessage.success('开始巡更，请按路线依次签到')
      // 模拟定位追踪
      this.startLocationTracking()
    },

    // 模拟定位追踪（实际项目中应使用百度地图定位SDK）
    startLocationTracking() {
      if (!this.isPatrolling) return

      // 模拟位置更新
      setTimeout(() => {
        if (this.map) {
          // 随机生成附近位置模拟移动
          const newLng = 116.404 + (Math.random() - 0.5) * 0.01
          const newLat = 39.915 + (Math.random() - 0.5) * 0.01
          this.map.panTo(new this.BMapGL.Point(newLng, newLat))
        }
        this.startLocationTracking()
      }, 5000)
    },

    // 签到操作
    checkIn(point) {
      this.currentPoint = point
      this.checkInForm = {
        pointId: point.id,
        pointName: point.name,
        result: '正常',
        remark: '',
        photoUrl: ''
      }
      this.checkInDialogVisible = true
    },

    // 处理照片上传
    handlePhotoUpload(file) {
      // 模拟照片上传，实际项目中应调用后端接口
      const reader = new FileReader()
      reader.onload = (e) => {
        this.checkInForm.photoUrl = e.target.result
      }
      reader.readAsDataURL(file.raw)
    },

    // 确认签到
    confirmCheckIn() {
      // 验证表单
      if (this.currentPoint.photoRequire && !this.checkInForm.photoUrl) {
        ElMessage.warning('该点位需要上传现场照片')
        return
      }

      // 保存签到记录
      this.patrolRecords.unshift({
        checkInTime: new Date().toLocaleString(),
        pointName: this.checkInForm.pointName,
        result: this.checkInForm.result,
        remark: this.checkInForm.remark
      })

      // 关闭弹窗
      this.checkInDialogVisible = false
      ElMessage.success('签到成功')
    }
  },
  beforeUnmount() {
    // 组件卸载时停止定位追踪
    this.isPatrolling = false
  }
}
</script>

<style scoped>
.patrol-container {
  padding: 20px;
}

.patrol-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.patrol-content {
  display: flex;
  gap: 20px;
  height: calc(100vh - 120px);
}

.map-wrapper {
  flex: 2;
  display: flex;
  flex-direction: column;
}

.map-container {
  width: 100%;
  flex: 1;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
}

.start-btn {
  margin-top: 10px;
  width: 100%;
}

.info-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10px;
  overflow-y: auto;
}

.preview-img {
  width: 100%;
  height: 200px;
  object-fit: contain;
  margin-top: 10px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
}
</style>